import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.core.converters.ArffSaver;

import weka.filters.Filter;
import weka.filters.unsupervised.attribute.*;

import java.io.File;
import java.util.Arrays;

public class WekaPreprocess
{
    public static void main(String[] args) {
        WekaPreprocess preprocess = new WekaPreprocess();

        String logfile = "";
        logfile = args[args.length - 1];

        String[] params = Arrays.copyOfRange(args, 0, args.length - 1);
        preprocess.execute(params);
    }

    /*
     * args[0] = task
     * args[1] = Data input file
     * args[2] = Data output file
     * args[3..] = parameters
     */
    protected void execute(String[] args) {
        // Extract arguments
        String logfile = "", task = "", inputFile = "", outputFile = "";
        String[] params = new String[0];
        try {
            task = args[0];
            inputFile = args[1];
            outputFile = args[2];
            if (args.length > 3) {
                params = Arrays.copyOfRange(args, 3, args.length);
            }
        }
        catch (Exception ex) {
            System.out.println("Error extracting parameters: " + Arrays.toString(args));
        }

        // Log task
        System.out.println("Call Preprocess " + task);
        System.out.println("    Input: " + inputFile + ", Output: " + outputFile);
        System.out.println("    Params: " + Arrays.toString(params));

        // Initialize data
        DataSource source = null;
        Instances data = null;
        try {
            source = new DataSource(inputFile);
            data = source.getDataSet();
        }
        catch (Exception ex) {
            System.out.println("Error reading file: " + inputFile);
        }

        // Initialize filter
        Object filter = null;
        try {
            Class <?> clazz = Class.forName(args[0]);
            filter = clazz.newInstance();
        }
        catch (Exception ex) {
            System.out.println("Error creating filter");
        }

        // Apply filter
        try {
            String[] fullParams = new String[4 + params.length];
            fullParams[0] = "-i";
            fullParams[1] = inputFile;
            fullParams[2] = "-o";
            fullParams[3] = outputFile;
            for(int i = 0; i < params.length; ++i)
                fullParams[i+4] = params[i];
            Filter.filterFile((Filter)filter, fullParams);
        }
        catch (Exception ex) {
            System.out.println("Error executing filter: " + ex.getMessage());
        }
    }
}
// Build: javac -cp weka.jar WekaPreprocess.java
// Run: java -Xmx2108m -cp weka.jar:. WekaPreprocess weka.filters.unsupervised.attribute.Normalize output_merged.csv output_normalized.arff preprocess
